package business

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/business"
	businessReq "github.com/flipped-aurora/gin-vue-admin/server/model/business/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type QuestionService struct {
}

// CreateQuestion 创建问题记录
// Author [piexlmax](https://github.com/piexlmax)
func (questionService *QuestionService) CreateQuestion(question *business.Question) (err error) {
	err = global.GVA_DB.Create(question).Error
	return err
}

// CreateQuestion 创建问题记录
// Author [piexlmax](https://github.com/piexlmax)
func (questionService *QuestionService) CreateQuestions(questionList []*business.Question) (err error) {
	err = global.GVA_DB.Create(questionList).Error
	return err
}

// DeleteQuestion 删除问题记录
// Author [piexlmax](https://github.com/piexlmax)
func (questionService *QuestionService) DeleteQuestion(question business.Question) (err error) {
	err = global.GVA_DB.Delete(&question).Error
	return err
}

// DeleteQuestionByIds 批量删除问题记录
// Author [piexlmax](https://github.com/piexlmax)
func (questionService *QuestionService) DeleteQuestionByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]business.Question{}, "id in (?)", ids.Ids).Error
	return err
}

// UpdateQuestion 更新问题记录
// Author [piexlmax](https://github.com/piexlmax)
func (questionService *QuestionService) UpdateQuestion(question business.Question) (err error) {
	err = global.GVA_DB.Save(&question).Error
	return err
}

// GetQuestion 根据id获取问题记录
// Author [piexlmax](https://github.com/piexlmax)
func (questionService *QuestionService) GetQuestion(id uint) (question business.Question, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&question).Error
	return
}

// GetQuestionInfoList 分页获取问题记录
// Author [piexlmax](https://github.com/piexlmax)
func (questionService *QuestionService) GetQuestionInfoList(info businessReq.QuestionSearch) (list []business.Question, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&business.Question{})
	var questions []business.Question
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&questions).Error
	return questions, total, err
}

// GetQuestionInfoList 通过问卷获取问题记录

func (questionService *QuestionService) GetQuestionInfoListByQuestionnaire(questionnaireUuid string) (list []business.Question, err error) {

	// 创建db
	db := global.GVA_DB.Model(&business.Question{})
	var questions []business.Question

	db = db.Where("questionnaire_uuid = ?", questionnaireUuid)

	err = db.Find(&questions).Error
	return questions, err
}
